package org.xqh.study.leetcode.algorithm;

import org.apache.poi.ss.formula.functions.T;

import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName DeepestTreeNodeSum
 * @Description https://leetcode-cn.com/problems/deepest-leaves-sum/submissions/
 * @Author xuqianghui
 * @Date 2021/1/12 11:30
 * @Version 1.0
 */
public class DeepestTreeNodeSum {

    public static void main(String[] args) {
        deepestLeavesSum(null);
    }

    /**
     * 层级最深 叶子节点 之和
     * @param root
     * @return
     */
    public static int deepestLeavesSum(TreeNode root) {
        AtomicInteger maxDeep = new AtomicInteger(0);
        AtomicInteger total = new AtomicInteger(0);
        TreeNode node = new TreeNode(0,
                new TreeNode(1, new TreeNode(3), null),
                new TreeNode(2, new TreeNode(5, new TreeNode(6), null), null));
        recursion(node, 1, maxDeep, total);
        System.out.println(total.intValue());
        return total.intValue();
    }

    public static void recursion(TreeNode node, int deep, AtomicInteger maxDeep, AtomicInteger total){
        if(Objects.isNull(node)){
            return ;
        }
        if(deep > maxDeep.intValue()){
            maxDeep.addAndGet(deep - maxDeep.intValue());
            total.addAndGet(0 - total.intValue() + node.val);
        }else if(deep == maxDeep.intValue()){
            total.addAndGet(node.val);
        }
        deep ++;
        recursion(node.left, deep, maxDeep, total);
        recursion(node.right, deep, maxDeep, total);
    }



    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }

        TreeNode(int x, TreeNode left, TreeNode right){
            this.val = x;
            this.left = left;
            this.right = right;
        }
    }
}
